package com.backmanage.intercept;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.backmanage.entity.LoginInfo;
import com.backmanage.entity.ReturnJSON;
import com.backmanage.utils.IpUtil;
import com.backmanage.utils.StringUtil;

/**
 * 权限拦截
 * @author tangjiang 
 * @version 创建时间：2016年6月24日 下午12:33:54
 * 类说明
 */
public class AuthorityIntercept implements HandlerInterceptor{

	private static Logger log = Logger.getLogger ( AuthorityIntercept.class.getName ());
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}
	/**
	 * 拦截没有登录的请求
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse resp,
			Object arg2) throws Exception {
		ReturnJSON json = new ReturnJSON();
		HttpSession  httpSession= request.getSession();
		String ip =(String) httpSession.getAttribute("ip");
		String id = httpSession.getAttribute("id").toString();
		
		if(!StringUtil.isNotEmpty(id)){
			json.setMsg("未登录");
			json.setCode(1);
			resp.getWriter().print(json.toString());
		}
		
		LoginInfo info = LoginInfo.listLoginInfo.get("login"+id);
		try {
			if( !info.getIp() .equals(IpUtil.getIpAddress(request)) ){
				json.setMsg(info.getMsg());
				json.setCode(1);
				resp.getWriter().print(json.toString());
			}
		} catch (IOException e) {
			log.error("获取IP错误"+e.getMessage());
			json.setMsg("获取IP错误");
			json.setCode(1);
			resp.getWriter().print(json.toString());
		}
		if(0 == json.getCode()){
			return true;
		}else{
			return false;
		}
		
	}

}
